package com.thinkgem.jeesite.androidpn.server.xmpp.handler;

import com.thinkgem.jeesite.androidpn.server.util.AddressUtils;
import com.thinkgem.jeesite.androidpn.server.xmpp.UnauthorizedException;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.ClientSession;
import com.thinkgem.jeesite.androidpn.server.xmpp.session.Session;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.notify.entity.NotiUser;
import com.thinkgem.jeesite.modules.notify.service.NotiUserService;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

/**
 * @Author: hf
 * @Description: 用户设备信息
 * @Date: 2018/12/21 14:08
 * @Version: 1.0
 */
public class IQUserEquipmentHandler extends IQHandler {

    private static final String NAMESPACE = "androidpn:iq:userequipment";

    private NotiUserService notiUserService = SpringContextHolder.getBean(NotiUserService.class);


    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        ClientSession session = sessionManager.getSession(packet.getFrom());
        IQ reply;
        if (session == null) {
            log.error("Session not found for key " + packet.getFrom());
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }

        if (session.getStatus() == Session.STATUS_AUTHENTICATED) {

            if (IQ.Type.get.equals(packet.getType())) {
                Element element = packet.getChildElement();

                String username = element.elementText("username");
                String appId = element.elementText("appid");
                String appedition = element.elementText("appedition");//app版本
                String mac = element.elementText("mac");
                String unitmodel = element.elementText("unitmodel");//设备型号
                String imsi = element.elementText("imsi");//国际移动识别码
                String deviceId = element.elementText("deviceid ");
                String ip = element.elementText("ip");

                //保存数据库
                try {
                    String address = AddressUtils.getAddress(ip);
                    NotiUser notiUser = notiUserService.getUserByUsernameAndAppid(username, appId);
                    if (notiUser != null) {
                        notiUserService.updatUserByUsernameAndAppid(appedition, mac, unitmodel, imsi, deviceId, address, ip, notiUser.getId());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public String getNamespace() {
        return NAMESPACE;
    }

}
